#!/usr/bin/env node

const http = require('http'),
  fs = require('fs');
//url:http://localhost:8080/add?x=2&y=3
let out = '';
http.createServer((req,res)=>{
  console.log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  if(req.url === '/'){
    if(req.method === 'GET'){
      let html = fs.readFileSync('./04-form.html').toString('utf8');
      res.end(html);
    }
    else if(req.method === 'POST'){
      let data = '';
      req.on('data',(chunk)=>{
        data+=chunk;
      });
      req.on('end',()=>{
        out = data;
        console.log(out);
        html = html.replace('%',out);
        res.end(html);
        //console.log(qs.parse(data));
      });
    }else{
      err(req,res);
    }
  }
  else{
    err(req,res);
  }

}).listen(3000);

function err(req,res){
  //console.log(res.statusCode);
  res.statusCode = 404;
  res.end(`${req.url} NOT FOUND`);
}
let html = `
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
    <title>login</title>
    </head>
    <body>
      <form method='post' action="http://192.168.17.144:30000/">
          <label>file:</label>
              <input type='file' name='file'/>
                  <br>
                      <label>password:</label>
                          <input type='password' name='password'/>
                              <br>
                                  <label>&nbsp;</label>
                                      <input type='submit' value='login'>
                                        </form>
                                        </body>
</html>
`;
